package com.pacifico.telebusca.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class TeleBuscaInterceptor implements HandlerInterceptor {

	private static Logger logger = Logger.getLogger(TeleBuscaInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub		
		StringBuffer url = request.getRequestURL();
		
		if(url.toString().contains("acceso")){			
			SecurityContextHolder.getContext().setAuthentication(null);
			request.getSession().invalidate();			
			return true;
		}
		
		String isEscuchar =  request.getParameter("escuchar");		
		if (url.toString().contains("mp3")){
			if (isEscuchar ==null){
				request.setAttribute("error", "No puede descargar archivo mp3.");
				String redirect = "https://" +request.getServerName() + ":"+request.getServerPort()+ request.getContextPath() + "/error";			
				response.sendRedirect(redirect);
				return false;	
			} else {
				return true;
			}
			
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

}
